package com.mission.schedule.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.QianDaoBackBean;
import com.mission.schedule.bean.QianDaoBean;
import com.mission.schedule.bean.QianDaoImgBackBean;
import com.mission.schedule.bean.QianDaoImgBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.db.DBHelper;
import com.mission.schedule.my160920.bean.FriendBackBean;
import com.mission.schedule.my160920.bean.FriendBean;
import com.mission.schedule.my160920.bean.FriendDeleteScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.bean.FriendDownBackBean;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.ImageFileCache;
import com.mission.schedule.utils.ImageGetFromIntenet;
import com.mission.schedule.utils.ImageMemoryCache;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DownQianDaoService extends Service {

    SharedPrefUtil sharedPrefUtil = null;
    App app = null;
    String downtime = "";
    String userid = "";
    String downImgTime = "";
    // ImageLoader imageLoader = null;
    private ImageMemoryCache memoryCache;
    private ImageFileCache fileCache;
    String imageType = "";
    int heigh = 0;
    String firstLogin = "";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.init("TAG");
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        app = App.getDBcApplication();
        sharedPrefUtil = new SharedPrefUtil(getApplication(),
                ShareFile.USERFILE);
        new Thread(new Runnable() {

            @Override
            public void run() {
                memoryCache = new ImageMemoryCache(getApplication());
                fileCache = new ImageFileCache();


                userid = sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE,
                        ShareFile.USERID, "");

                downtime = sharedPrefUtil.getString(getApplication(),
                        ShareFile.USERFILE, ShareFile.QIANDAODOWNDATE, "2017-01-01%2B00:00:00");

                downImgTime = sharedPrefUtil.getString(getApplication(),
                        ShareFile.USERFILE, ShareFile.QIANDAODOWNIMGDATE, "");
                if (intent == null) {
                    return;
                }
                heigh = intent.getIntExtra("heigh", 0);
                firstLogin = intent.getStringExtra("firstLogin");
                if (heigh == 0) {
                    return;
                } else {
                    if (heigh > 0 && heigh <= 1200) {
                        imageType = "2";
                    } else if (heigh > 1200 && heigh <= 1800) {
                        imageType = "3";
                    } else if (heigh > 1800 && heigh < 2560) {
                        imageType = "4";
                    }
                    if ("0".equals(firstLogin)) {
                        downtime = "2017-01-01%2B00:00:00";
                    }
                    LoadData();
                }
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }

    private void LoadData() {
        String downqiandaoPath = URLConstants.签到下行 + downtime;
        StringRequest request = new StringRequest(Method.GET, downqiandaoPath,
                new Listener<String>() {

                    @Override
                    public void onResponse(final String result) {
                        new Thread(new Runnable() {
                            public void run() {
                                if (!TextUtils.isEmpty(result)) {
                                    Gson gson = new Gson();
                                    try {
                                        QianDaoBackBean backBean = gson.fromJson(result, QianDaoBackBean.class);
                                        sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE,
                                                ShareFile.QIANDAODOWNDATE, backBean.downTime.replace("T", "%2B"));
                                        List<QianDaoBean> beans;
                                        if (backBean.status == 0) {
                                            beans = backBean.list;
                                            if (beans != null && beans.size() > 0) {
                                                for (QianDaoBean bean : beans) {
                                                    int count = app.CheckCountQianDaoData(bean.calendar);
                                                    if (count == 0) {
                                                        app.insertQianDaoData(bean.id, bean.integral,
                                                                bean.calendar, bean.lunarCalendar, bean.holiday,
                                                                bean.lunarHoliday, bean.solarTerms, bean.imgNum,"", "");
                                                    } else {
                                                        app.updateQianDaoData(bean.id, bean.integral,
                                                                bean.calendar, bean.lunarCalendar, bean.holiday,
                                                                bean.lunarHoliday, bean.solarTerms, bean.imgNum, "", "");
                                                    }
                                                }
                                            }

                                        }
                                    } catch (JsonSyntaxException e) {
                                        e.printStackTrace();
                                    }
                                }
                                downLoadImage();
                            }
                        }).start();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                downLoadImage();
            }
        });
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    private void downLoadImage() {
        String downqiandaoImgPath = URLConstants.签到图片下载;
        StringRequest request1 = new StringRequest(Method.POST, downqiandaoImgPath, new Listener<String>() {

            @Override
            public void onResponse(final String result) {
                new Thread(new Runnable() {
                    public void run() {
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            try {
                                QianDaoImgBackBean backBean = gson.fromJson(result, QianDaoImgBackBean.class);
                                sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.QIANDAODOWNIMGDATE, backBean.downTime.replace("T", " "));
                                List<QianDaoImgBean> beans;
                                if (backBean.status == 0) {
                                    beans = backBean.list;
                                    if (beans != null && beans.size() > 0) {
                                        for (QianDaoImgBean bean : beans) {
                                            int count = app.CheckCountQianDaoImgData(bean.signNum);
                                            if (count != 0) {
                                                app.updateQianDaoImgData(bean.signNum, bean.imgPath.replace("\\", ""), "");
                                            }
                                            String dicr = Environment.getExternalStorageDirectory()+"/DCIM/";
                                            File outfile = new File(dicr,"TimeApp");
                                            // 如果文件不存在，则创建一个新文件
                                            if (!outfile.isDirectory()) {
                                                try {
                                                    outfile.mkdir();
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            File file = new File(outfile + "/" + bean.imgPath.replace("\\", "").replace('/', '0'));
                                            if (!file.exists()){
                                                if (!"".equals(StringUtils.getIsStringEqulesNull(bean.imgPath))) {
                                                    String path = URLConstants.图片 + bean.imgPath.replace("\\", "") + "&imageType=10&imageSizeType=1";
                                                    Intent intent = new Intent(getApplication(), DownImageService.class);
                                                    intent.setAction("downimage");
                                                    intent.putExtra("url", path);
                                                    intent.putExtra("name", bean.imgPath.replace("\\", "").replace('/', '0'));
                                                    startService(intent);
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("downTime", DateUtil.oneMonth());//
                map.put("imgType", "1");
                return map;
            }
        };
        request1.setTag("down");
        request1.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request1);
    }


    public Bitmap getBitmap(String url) {
        // 从内存缓存中获取图片
        Bitmap result = memoryCache.getBitmapFromCache(url);
        if (result == null) {
            // 文件缓存中获取
            result = fileCache.getImage(getApplication(), url);
            if (result == null) {
                // 从网络获取
                result = ImageGetFromIntenet.downloadBitmap(url);
                if (result != null) {
                    fileCache.saveBitmap(result, url, 0);
                    memoryCache.addBitmapToCache(url, result);
                }
            } else {
                // 添加到内存缓存
                memoryCache.addBitmapToCache(url, result);
            }
        }
        return result;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        App.getHttpQueues().cancelAll("down");
    }

    /**
     * @param oldPath String 原文件路径
     * @param newPath String 复制后路径
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    Bitmap bitmap;
    String imageName;

    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public Bitmap GetImageInputStream(String imageurl) {
        URL url;
        HttpURLConnection connection = null;
        Bitmap bitmap = null;
        try {
            url = new URL(imageurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * 异步线程下载图片
     */
    class Task extends AsyncTask<String, Integer, Void> {

        protected Void doInBackground(String... params) {
            bitmap = GetImageInputStream((String) params[0]);
            imageName = params[1];
            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Log.e("TAG", "downimageok");
            SavaImage(bitmap, Environment.getExternalStorageDirectory().getPath() + "/YourAppFolder/data", imageName);
        }

    }

    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public void SavaImage(Bitmap bitmap, String path, String imagename) {
        File file = new File(path);
        FileOutputStream fileOutputStream = null;
        //文件夹不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            fileOutputStream = new FileOutputStream(path + "/" + imagename + ".png");
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
